<template>
    <div class="component-upload-image">
      <el-upload
        ref="imageUpload"
        multiple
        action="#"
        :auto-upload="false"
        list-type="picture-card"
        :limit="1"
        :on-exceed="handleExceed"
        :before-remove="handleDelete"
        :on-change="handleUploadSuccess"
        :show-file-list="true"
        :file-list="fileList"
        :on-preview="handlePictureCardPreview"
        :class="{ hide: uploadFileList.length >= limit }"
      >
        <el-icon class="avatar-uploader-icon">
          <plus />
        </el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible" title="预览" width="800px" append-to-body>
        <img :src="dialogImageUrl" style="display: block; max-width: 100%; margin: 0 auto" />
      </el-dialog>
    </div>
  </template>

  <script setup lang="ts">
  // import { OssVO ,itemValue} from '@/api/system/oss/types';
  import { propTypes } from '@/utils/propTypes';

  const props = defineProps({
    modelValue: {
      type: [String, Object, Array],
      default: () => []
    },
    // 图片数量限制
    limit: propTypes.number.def(1),
    // 大小限制(MB)
    fileSize: propTypes.number.def(10),
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: propTypes.array.def(['png', 'jpg', 'jpeg']),
    // 是否显示提示
    isShowTip: {
      type: Boolean,
      default: true
    },
    // 是否支持压缩，默认否
    compressSupport: {
      type: Boolean,
      default: false
    },
    // 提示信息
    tipInfo: {
      type: String,
      default: undefined
    },
    // 压缩目标大小，单位KB。默认300KB以上文件才压缩，并压缩至300KB以内
    compressTargetSize: propTypes.number.def(300)
  });

  const { proxy } = getCurrentInstance() as ComponentInternalInstance;
  const emit = defineEmits(['update:modelValue','change','del']);
  const number = ref(0);
  const uploadList = ref<any[]>([]);
  const dialogImageUrl = ref('');
  const dialogVisible = ref(false);
  const fileList = ref<any[]>([]);
  const uploadFileList = ref([])
  const imageUploadRef = ref<ElUploadInstance>();


  /** 上传前loading加载 */
  const handleBeforeUpload = (file: any) => {
    console.log(file);

    let isImg = false;
    if (props.fileType.length) {
      let fileExtension = '';
      if (file.name.lastIndexOf('.') > -1) {
        fileExtension = file.name.slice(file.name.lastIndexOf('.') + 1);
      }
      isImg = props.fileType.some((type: any) => {
        if (file.type.indexOf(type) > -1) return true;
        if (fileExtension && fileExtension.indexOf(type) > -1) return true;
        return false;
      });
    } else {
      isImg = file.type.indexOf('image') > -1;
    }
    if (!isImg) {
      proxy?.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join('/')}图片格式文件!`);
      return false;
    }
    if (props.fileSize) {
      const isLt = file.size / 1024 / 1024 < props.fileSize;
      if (!isLt) {
        proxy?.$modal.msgError(`上传头像图片大小不能超过 ${props.fileSize} MB!`);
        return false;
      }
    }
  };

  // 文件个数超出
  const handleExceed = () => {
    proxy?.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
  };

  // 上传成功回调
  const handleUploadSuccess = (file: UploadFile, files: any) => {
    if (props.fileSize) {
      const isLt = file.size / 1024 / 1024 < props.fileSize;
      if (!isLt) {
        proxy?.$modal.msgError(`上传头像图片大小不能超过 ${props.fileSize} MB!`);
        fileList.value = []
        return false;
      }
    }
    uploadFileList.value = [ file.raw];
    uploadedSuccessfully();
  };

  // 删除图片
  const handleDelete = (file: UploadFile): boolean => {
    uploadFileList.value = [ ];
    emit('update:modelValue', null);
    // emit('change', null)
    emit('del', null)
    return true;
  };

  // 上传结束处理
  const uploadedSuccessfully = () => {
      emit('update:modelValue', uploadFileList.value[0]);
      emit('change', uploadFileList.value[0])
  };

  // 上传失败
  const handleUploadError = () => {
    proxy?.$modal.msgError('上传图片失败');
    proxy?.$modal.closeLoading();
  };

  // 预览
  const handlePictureCardPreview = (file: any) => {
    dialogImageUrl.value = file.url;
    dialogVisible.value = true;
  };

  watch(() => props.modelValue, (val) => {
    if (val) {
      uploadFileList.value = [val]
      fileList.value = [{name: val, url: val,}]
    } else {
      uploadFileList.value = [];
      fileList.value = []
    }
  },{
    deep: true,
    immediate: true
  });
  </script>

  <style scoped lang="scss">
  // .el-upload--picture-card 控制加号部分
  :deep(.hide .el-upload--picture-card) {
    display: none;
  }
  </style>
